#!/usr/bin/python
# this program will help you peek the data that Parameter Designer is uploading
# into the controller, without a controller. Just cross-connect the programming
# cable to yet another RS232-UART adapter (e.g. RX to TX and TX to RX), and
# launch this program on the second serial port, it will "simulate" a real
# controller.

import sys, time

try:
    import serial
except:
    print "You must have the PySerial Python library installed for this program to work!"
    sys.exit (-1)

ser = serial.Serial ("/dev/ttyUSB2", 38400, serial.EIGHTBITS, serial.PARITY_NONE,
    serial.STOPBITS_TWO, timeout=1.5)

def read_data ():
    while True:
        try:
            c = ser.read (1)
            if c == '8':
                ser.flushInput ()
                ser.write ('U')
                data = bytearray ()
                while True:
                    c = ser.read ()
                    if (len(data) == 0) and (c == '8'):
                        raise BaseException ('Unexpected 8')
                    if not c:
                        raise BaseException ('Unexpected EOF')
                    data.extend (c)
                    if len (data) >= 32:
                        break

                ser.write ('Q')
                ser.write ('R')

                print "\nGot data:"
                for x in range (len (data)):
                    if ((x & 15) == 0):
                        sys.stdout.write ("\n%04x  " % x)
                    sys.stdout.write (" %02x " % data [x])
                sys.stdout.write ("\n")
                crc = 0
                for x in range (len (data)):
                    if ((x & 15) == 0):
                        sys.stdout.write ("\n%04x  " % x)
                    sys.stdout.write ("%3d " % data [x])
                    if x < len (data) - 1:
                        crc = crc ^ data [x]
                sys.stdout.write ("\n")
                print "crc = %04x (%d)" % (crc, crc % 256)
                break
        except KeyboardInterrupt:
            print "Cancelled"
            break
        except BaseException:
            continue


read_data ()

time.sleep (1)
ser.close ()
